/**
 * Created by wangshaohua on 2018/1/13.
 */
moduleContent.controller("ContentQuizDetail", function (EnumService, GaugeTopicGroupResource, LanguageService, ExerciseContentResource, $$CambioConfig, UploadFileService, $scope, $log, $state, $stateParams, LoadingService, ConstantService, DialogService) {
    initPage($scope);
    $scope.$on("$viewContentLoaded", function () {
        //$scope.reset();
        pageOnLoad();
        ConstantService.addState($state.current, true, LanguageService.language('测试课程详细'));
        $scope.contentId = $stateParams.contentId;
        $scope.selectTab('tabInfo');
    });

    $scope.currentTabId = 0;
    $scope.selectTab = function (tabId) {
        if (tabId === 'tabInfo') {
            $scope.loadDetail();
            $scope.currentTabId = tabId;
        }
        if (tabId === 'tabTopic') {
            $scope.loadTopic();
            $scope.currentTabId = tabId;
        }
    };

    // ------------------------------------------------------------------------------------------------------
    $scope.loadDetail = function () {
        ExerciseContentResource.findById({id: $scope.contentId}, {}, function (queryResult) {
            $log.debug("查询结果", queryResult.data);
            $scope.currentContentQuiz = queryResult.data;
            //LoadingService.hide();
        });
    };


    $scope.updateContent = function () {
        Alert.confirm(function () {
            ExerciseContentResource.updateQuiz({}, $scope.currentContentQuiz, function (result) {
                Alert.success();
            });
        })
    }

    // ------------------------------------------------------------------------------------------------------
    // ------------------------------------------------------------------------------------------------------

    $scope.loadTopic = function () {
        GaugeTopicGroupResource.findByGaugeTemplateId({gaugeTemplateId: $scope.currentContentQuiz.targetId}, function (result) {
            $log.debug("当前量表题目组", result);
            $scope.currentGaugeTopicGroup = result;
        });
    }

    $scope.addTopic = function () {
        DialogService.open("addQuizTopic", $scope);
    };

    var copyTopic = function (topic) {
        var result = {};
        result.itemCode = topic.itemCode;
        result.type = topic.type;
        result.content = topic.content;
        result.attributes = [];
        angular.forEach(topic.attributes, function (attribute) {
            var attrTemp = {};
            attrTemp.sort = attribute.sort;
            attrTemp.score = attribute.score;
            attrTemp.content = attribute.content;
            result.attributes.push(attrTemp);
        });
        return result;
    };

    //按本题新增题目
    $scope.addTopicTemp = function (gaugeTopic) {
        var newTopic = copyTopic(gaugeTopic);
        $scope.currentGaugeTopicGroup.gaugeTopics.push(newTopic);
    };

    $scope.editTopic = function (topic) {
        $scope.currentTopic = topic;
        $scope.editingTopic = angular.copy($scope.currentTopic);
        $scope.editingTopic.typeOption = EnumService.getEnumObject($scope.editingTopic.type, "GaugeTopicTypeEnum");
        DialogService.open("editQuizTopic", $scope);
    };

    $scope.deleteTopic = function (topic) {
        Alert.confirm(function () {
            for (var i = 0; i < $scope.currentGaugeTopicGroup.gaugeTopics.length; i++) {
                if (topic == $scope.currentGaugeTopicGroup.gaugeTopics[i]) {
                    $scope.currentGaugeTopicGroup.gaugeTopics.remove(i);
                }
            }
            $scope.$apply();
        });
    };

    $scope.addAttribute = function (topic) {
        $scope.currentTopic = topic;
        DialogService.open("addQuizTopicAttribute", $scope);
    };

    $scope.editAttribute = function (attribute) {
        $scope.currentAttribute = attribute;
        $scope.editingAttribute = angular.copy($scope.currentAttribute);
        DialogService.open("editQuizTopicAttribute", $scope);
    };

    $scope.deleteAttribute = function (topic, attribute) {
        Alert.confirm(function () {
            for (var i = 0; i < topic.attributes.length; i++) {
                if (attribute == topic.attributes[i]) {
                    topic.attributes.remove(i);
                }
            }
            $scope.$apply();
            $timeout(function () {
                Alert.success();
            }, 300);
        });
    };

    $scope.save = function () {
        //LoadingService.show();
        GaugeTopicGroupResource.save($scope.currentGaugeTopicGroup, function (currentGaugeTopicGroupResult) {
            $log.debug("量表题目保存结果", currentGaugeTopicGroupResult);
            $scope.currentGaugeTopicGroup = currentGaugeTopicGroupResult;
            //LoadingService.hide();
            Alert.success();
        })
    };

    $scope.refresh = function () {
        $scope.queryPara = {};
        $scope.$broadcast("init-select");
    };

    // ------------------------------------------------------------------------------------------------------
    // ------------------------------------------------------------------------------------------------------
    function checkWBJson(rawJson) {
        var first = rawJson[0];
        /** @namespace first.Answer */
        /** @namespace first.Title */
        return (first && first.Title && first.Type && first.A && first.B && first.Answer);
    }

    function addAttribute(answer, itemCode, sort, content, currentTopic) {
        if (StringUtils.isNlOrUndOrEmpty(content)) {
            return;
        }
        var currentAttribute = {};
        currentAttribute.sort = sort;
        currentAttribute.score = answer.includes(itemCode) ? 1 : 0;
        currentAttribute.content = content;
        currentTopic.attributes.push(currentAttribute);
    }

    function jsonToQuizTopicWB(rawJson) {
        var topicList = [];
        rawJson.forEach(function (rawQuizTopic, index) {
            var currentTopic = {};
            currentTopic.itemCode = index + 1;
            if (parseInt(rawQuizTopic['Type']) === 0) {
                currentTopic.type = 'SELECT'
            } else {
                currentTopic.type = 'CHECKBOX_BOOLEAN';
            }
            currentTopic.content = rawQuizTopic['Title'];
            currentTopic.attributes = [];
            addAttribute(rawQuizTopic.Answer, 'A', 1, rawQuizTopic.A, currentTopic);
            addAttribute(rawQuizTopic.Answer, 'B', 2, rawQuizTopic.B, currentTopic);
            addAttribute(rawQuizTopic.Answer, 'C', 3, rawQuizTopic.C, currentTopic);
            addAttribute(rawQuizTopic.Answer, 'D', 4, rawQuizTopic.D, currentTopic);
            addAttribute(rawQuizTopic.Answer, 'E', 5, rawQuizTopic.E, currentTopic);
            addAttribute(rawQuizTopic.Answer, 'F', 6, rawQuizTopic.F, currentTopic);
            topicList.push(currentTopic);
        });
        return topicList;
    }

    /**
     * "[{
     *      "Title":"“倒拿或乱用工具会导致事故”，这种说法正确吗？",
     *      "Type":"0",
     *      "question_knowledge":"正确",
     *      "level":"0",
     *      "Pk":"1",
     *      "Map":"1",
     *      "A":"正确",
     *      "B":"错误",
     *      "Answer":"A"
     *  },{
     *      "Title":"文中，梯子、梯凳有几条安全须知？",
     *      "Type":"0",
     *      "question_knowledge":"9条",
     *      "level":"0",
     *      "Pk":"1",
     *      "Map":
     *      "1",
     *      "A":"9条",
     *      "B":"6条",
     *      "C":"7条",
     *      "D":"8条",
     *      "Answer":"A"
     *  }]"
     * @param workbook
     */
    $scope.readWB = function (workbook) {
        /* DO SOMETHING WITH workbook HERE */
        $log.debug(workbook);
        var rawJson = XLS.utils.sheet_to_json(workbook.Sheets[workbook.SheetNames[0]]);
        $log.debug("excel数据", rawJson);
        if (!checkWBJson(rawJson)) {
            Alert.error(LanguageService.language('数据格式错误!'));
        } else {
            var topicList = jsonToQuizTopicWB(rawJson);
            $log.debug("转换后数据", topicList);
            //$scope.currentQuizTopicGroup.gaugeTopics = topicList;
            $scope.currentContentQuiz.topics = topicList;
            $scope.$apply();
        }
    };


    // ------------------------------------------------------------------------------------------------------
    // ------------------------------------------------------------------------------------------------------

    $scope.uploadPicture = function ($files) {
        if ($files && $files[0]) {
            UploadFileService.uploadFile($files[0], $$CambioConfig.UPLOAD_URL, 'IMG', $scope).then(function (o) {
                $scope.currentContentQuiz.picture = o.id;
            });
        }
    };

    // ------------------------------------------------------------------------------------------------------
    // ------------------------------------------------------------------------------------------------------


    // ------------------------------------------------------------------------------------------------------

});